//
// Created by 徐套 on 2023/10/1.
//
// 上位机服务器端

#ifndef CAR_CLOUD_SERVER_UPPER_COMPUTER_SERVER_H
#define CAR_CLOUD_SERVER_UPPER_COMPUTER_SERVER_H

#include <string>
#include "cstdlib"
#include "common/clock.hpp"
#include "processor/car_contral.h"
#include <vector>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <iostream>
#include <thread>

#define MAXTIMEOUT 20
#define SENDTIME 20
// 发送间隔 20ms
//constexpr int SENDTIME = 20;

class upper_computer_server {
public:

    upper_computer_server(unsigned int port, int client, std::string &ip_upper, Clock_time *time0, car_contral * car){
        start = true;
        client_tcp = client;
        port_udp = port;
        upper_ip = ip_upper;
        time_ = time0;
        car_c = car;
        heart_time = 0;
        client_udp = socket(AF_INET, SOCK_DGRAM, 0);
    }

    ~upper_computer_server(){
        start = false;
        std::cout<<"delete upper server"<<std::endl;
        if (client_udp != -1){
            close(client_udp);
        }
        if (client_tcp != -1){
            close(client_tcp);
        }
    }

    void send_msg_by_udp(AllCar &car);

    bool send_msg_by_tcp(std::string& msg);

    bool init_upper_server();

    void tcp_connect();

    void udp_connect();

    void send_car_state();

    void heart_beat_time();

    unsigned int get_time_late() const;

    bool is_alive() const;

private:
    Clock_time *time_;
    car_contral* car_c;
    unsigned int time_late;
    std::string time_recv;
    std::string upper_ip;
    int client_tcp;
    int client_udp;
    struct sockaddr_in server_addr_;
    sockaddr_in client_addr_;
    socklen_t server_len_;
    socklen_t client_len_;
    unsigned int port_udp;
    bool start;
    bool udp_start;
    int heart_time;
};


#endif //CAR_CLOUD_SERVER_UPPER_COMPUTER_SERVER_H
